package com.pclong.sql;

import java.sql.Connection;
import java.sql.DriverManager;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import com.pclong.util.debug.Debug;

public class DBConnect {
	
	private static String DRIVERCLASS = "";
	private static String DATABASEURL = "";
	private static String DATABASEJNDI = "";
	private static boolean useJNDIBoolean = false;
	private static Debug debug = null;
	
	static {
		DRIVERCLASS = DataSourceProvider.getDriverClass();
		DATABASEURL = DataSourceProvider.getDatabaseUrl();
		DATABASEJNDI = DataSourceProvider.getDatabaseJNDI();
		useJNDIBoolean = DataSourceProvider.isUseJNDI();
		debug = DataSourceProvider.getDebug(DBConnect.class);
	}

	/**
	 * 获取数据库连接。
	 */
	public static Connection getConnection(){
		Connection connection = null;	
		if(useJNDIBoolean){
			Context initContext = null;
			try {
				initContext = new InitialContext();
				Context envCtx = (Context) initContext.lookup("java:comp/env");
				DataSource dataSource = (DataSource) envCtx.lookup(DATABASEJNDI);
				connection = dataSource.getConnection();
			} catch (Exception e) {
				debug.exception(e);
			}
		}else{
			try {
				Class.forName(DRIVERCLASS).newInstance();
				connection = DriverManager.getConnection(DATABASEURL);
			} catch (Exception e) {
				debug.exception(e);
			}
		}
		
		return connection;
	}

	/**
	 * 关闭数据库连接。
	 */
	public static void closeConnection(Connection connection) {
		try {
			connection.close();
		} catch (Exception e) {
			debug.exception(e);
		}
	}
}
